package net.sf.nlp.ltag.parser;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import net.sf.nlp.ltag.data.LTAGTree;
import net.sf.nlp.ltag.data.Word;
import net.sf.nlp.ltag.parser.dot.DotAlg;
import net.sf.nlp.ltag.parser.dot.DotAlgMultiThread;
import net.sf.nlp.ltag.parser.earley.EarleyAlg;
import net.sf.nlp.ltag.parser.earley.EarleyAlgMultiThread;
import net.sf.nlp.ltag.util.LTAG;

public class LTAGParser implements Parser 
{
	protected static Logger logger =  Logger.getLogger(LTAGParser.class);
	
	private static Map<String, List<LTAGTree>> ltagMap = LTAGLoad.loadTrees();
	private ParserAlg alg = null;
	
	public LTAGParser()
	{
		if (Boolean.valueOf(LTAG.ltagProperties.getProperty("USER_EARLEY_PARSER")))
		{
			if (Boolean.valueOf(LTAG.ltagProperties.getProperty("MULTI_THREAD")))
				alg = new EarleyAlgMultiThread(ltagMap);
			else
				alg = new EarleyAlg(ltagMap);
		}
		else
		{
			if (Boolean.valueOf(LTAG.ltagProperties.getProperty("MULTI_THREAD")))
				alg = new DotAlgMultiThread(ltagMap);
			else
				alg = new DotAlg(ltagMap);
		}
	}
	
	@Override
	public List<ParserTree> parser(String text) {
		
		List<Word> words = new ArrayList<Word>();
		String[] items = text.split(" ");
		int index;
		int wordIndex = 0;
		
		for (String item : items)
		{
			item = item.trim();
			if (item.length() == 0)
				continue;
			
			index = item.lastIndexOf("/");
			
			Word word = new Word();
			word.setLexical(item.substring(0, index).trim());
			word.setPos(item.substring(index + 1).trim().toUpperCase());
			word.setWordIndex(wordIndex++);
			
			words.add(word);
		}
		
		return parser(words);
	}
	
	@Override
	public List<ParserTree> parser(List<Word> words) 
	{
		List<ParserTree> parseTrees = new ArrayList<ParserTree>();
		
		try
		{
			List<ParserTree> parserTrees = alg.calculate(words);
			
			logger.info("-----------------PARSER TREE-----------------");
			for (ParserTree parserTree : parserTrees)
			{
				parseTrees.add(parserTree);
				
				logger.info(parserTree.getTree().toString());
			}
			logger.info("---------------------------------------------");			
		}
		catch(Exception ex)
		{
			logger.error(ex, ex);
		}
		
		return parseTrees;
	}

	public static void main(String[] args)
	{
		//String text = "企业/NN 投入/VV 一亿/CD 元/M";
		//String text = "设立/VV 重庆/NR 直辖市/NN 的/DEC 议案/NN 若/CS 获得/VV 通过/NN";
		//String text = "美/NR 驻华/JJ 大使/NN 呼吁/VV 美/NR 采取/VV 建设性/NN 对/P 华/NR 政策/NN";
		String text = "四川省/NR 和/CC 安徽省/NR 是/VC 首次/AD 参加/VV";
		//String text = "对/P 此/PN ，/PU 英国/NR 政府/NN 遂/AD 决定/VV 将/BA 其/PN 对/P 马岛/NR 附近/NN 水域/NN 管辖权/NN 由/P 150/CD 海里/M 扩大/VV 到/VV 200/CD 海里/M";
				
		long startTime = System.currentTimeMillis();
		
		LTAGParser parser = new LTAGParser();
		
		parser.parser(text);
		
		logger.error("Total time used: " + (System.currentTimeMillis() - startTime));
	}
	
}
